import 'dart:async';
import 'dart:convert';

import 'package:after_sale_plugin/package_bridge.dart';
import 'package:after_sale_plugin/package_data_center.dart';
import 'package:after_sale_plugin/package_event.dart';
import 'package:after_sale_plugin/pages/models/order_model.dart';
import 'package:after_sale_plugin/pages/models/vehicle_model.dart';
import 'package:after_sale_plugin/routes.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:wechat_assets_picker_plus/wechat_assets_picker_plus.dart';
import '../../constant.dart';
import '../models/vehicle_err_back_model.dart';
import 'state.dart';

class EditOrderController extends LxBaseScrollOpacityController {
  // 状态
  EditOrderState state = EditOrderState();

  @override
  onInit() async {
    super.onInit();

    PackageEvent.getRegion((p0) {
      state.isChineseRegion.value = p0;
    });

    // 监听
    _listen();

    state.reportOrderInfo.reportVehicleName.value =
        PackageDataCenter.vehicleDataModel.name.value;
    state.reportOrderInfo.sn = PackageDataCenter.vehicleDataModel.sn ?? "";
    // 车辆连接状态
    state.bleConnected.value =
        PackageDataCenter.vehicleDataModel.isConnected ?? false;

    _checkUnCompleteEditOrder();
  }

  // 检查未完成的编辑订单
  _checkUnCompleteEditOrder() async {
    String? localEditOrderInfo =
        SharedPreferencesService.to.getString(EDIT_ORDER_INFO);
    if (localEditOrderInfo != null && localEditOrderInfo.isNotEmpty) {
      var model = ReportOrderInfo.fromMap(jsonDecode(localEditOrderInfo));
      refresh({bool clear = false}) {
        state.reportOrderInfo.reportVehicleName.value = clear
            ? state.reportOrderInfo.reportVehicleName.value
            : model.reportVehicleName.value;
        state.reportOrderInfo.sn = clear ? state.reportOrderInfo.sn : model.sn;
        state.reportOrderInfo.reportPersonName.value =
            clear ? "" : model.reportPersonName.value;
        state.reportOrderInfo.reportPhoneNumber.value =
            clear ? "" : model.reportPhoneNumber.value;
        state.reportOrderInfo.reportType.value =
            clear ? -1 : model.reportType.value;
        state.reportOrderInfo.reportTypeDesc.value =
            ReportType.getTypeByNum(state.reportOrderInfo.reportType.value)
                    ?.title ??
                "";
        state.reportOrderInfo.problemContent.value =
            clear ? "" : model.problemContent.value;
        RxList<AssetModel> tempModels = model.assetModels;
        state.reportOrderInfo.assetModels.value =
            clear || model.assetModels.isEmpty ? [AssetModel.add] : tempModels;
        if (!state.reportOrderInfo.assetModels.any((model) => model.isAdd)) {
          if (state.reportOrderInfo.assetModels.length < 9) {
            state.reportOrderInfo.assetModels.add(AssetModel.add);
          }
        }
      }

      refresh(clear: true);
      Future.delayed(const Duration(milliseconds: 300), () {
        // 是否继续 正在编辑的订单
        PackageEvent.showConfirmAlert(
          AppLanguageUtil.to.whetherToContinueReportOrderPrompts,
          confirmTitle: AppLanguageUtil.to.titleYes,
          cancelTitle: AppLanguageUtil.to.titleNo,
          confirmCallBack: (p0) {
            if (p0) {
              SharedPreferencesService.to.setString(EDIT_ORDER_INFO, '');
              refresh();
            }
          },
        );
      });
    }
  }

  // 监听
  _listen() {
    // 需要监听的文本内容数量（报修车辆/联系人/联系人电话/报修类型/问题描述/上传的图片视频）
    int listenCounts = state.isChineseRegion.value ? 6 : 5;
    // 监听 车辆名称
    state.reportOrderInfo.reportVehicleName.listen((p0) {
      state.booleansMap[AppLanguageUtil.to.titleReportVehicleType] =
          p0.isNotEmpty;
    });

    // 监听 报修人姓名
    if (state.isChineseRegion.value) {
      state.reportOrderInfo.reportPersonName.listen((p0) {
        state.booleansMap[AppLanguageUtil.to.titleReportPersonName] =
            p0.isNotEmpty;
      });
    }

    // 监听 报修人电话
    state.reportOrderInfo.reportPhoneNumber.listen((p0) {
      state.booleansMap[AppLanguageUtil.to.titleReportPersonNumber] =
          p0.isNotEmpty;
    });

    // 监听 报修类型
    state.reportOrderInfo.reportType.listen((p0) {
      state.booleansMap[AppLanguageUtil.to.titleReportType] = p0 >= 0;
    });

    // 监听 报修内容
    state.reportOrderInfo.problemContent.listen((p0) {
      state.booleansMap[AppLanguageUtil.to.titleProblemDesc] = p0.isNotEmpty;
    });

    // 监听 资源文件
    state.reportOrderInfo.assetModels.listen((p0) {
      state.assetUploadCompleted.value =
          p0.every((element) => element.src.isNotEmpty || element.isAdd);

      state.booleansMap[AppLanguageUtil.to.titleUploadPhoptoAndVideo] =
          state.reportOrderInfo.assetModels.length > 1;
    });

    state.booleansMap.stream.listen((p0) {
      if (AfterSalePluginBridge.to.isRunAlone) {
        state.allowedSubmit.value = true;
      } else {
        if (listenCounts != state.booleansMap.keys.length) return;
        // 所有值都为true，按钮高亮
        state.allowedSubmit.value = state.booleansMap.values.every((b) => b);
      }
    });
  }

  // 开始检测
  void startCheckErrAction() {
    check() {
      // 检测
      PackageEvent.startCheckErr((p0) {
        AfterSalePluginBackModel model = p0;
        state.isCheckedErr.value = true;
        state.reportOrderInfo.diagnosis.value.url = model.url;
        state.reportOrderInfo.diagnosis.value.code = model.code;
        state.reportOrderInfo.diagnosis.value.descriptions.value = model
            .errorList.value
            ?.map((e) => DiagnosisDescriptionModel.fromMap(e))
            .toList();
      });
    }

    if (state.bleConnected.value) {
      check();
    } else {
      if (state.reportOrderInfo.reportVehicleName.value.isEmpty) {
        // 去选择车型
        PackageEvent.showToast(
            AppLanguageUtil.to.toastSelectRepairModelBeforeCheckErr);
      } else {
        // 连接蓝牙
        PackageEvent.connectVehicle(
          (p0) {
            // 成功才返回
            state.bleConnected.value = true;
            PackageDataCenter.vehicleDataModel = VehicleDataModel.fromMap(
                jsonDecode(p0) as Map<dynamic, dynamic>);
            check();
          },
          param: PackageDataCenter.vehicleDataModel.sn,
        );
      }
    }
  }

  // 提交
  void submitAction() {
    bool isSubmited = false;
    submit() {
      if (isSubmited) return;
      PackageEvent.newOrder((p0) {
        String id = p0;
        if (id.isNotEmpty) {
          PackageEvent.showConfirmAlert(
            AppLanguageUtil.to.submitOrderSuccessPrompts,
            confirmTitle: AppLanguageUtil.to.titleOK,
            isShowCancel: false,
            confirmCallBack: (p0) {
              Get.offNamed(Routes.orderDetail, arguments: id);
            },
          );
        }
      }, param: state.reportOrderInfo.toJson());
      isSubmited = true;
    }

    if (!state.allowedSubmit.value) return;
    if (state.assetUploadCompleted.value) {
      submit();
    } else {
      PackageEvent.showLoading();
      state.assetUploadCompleted.listen((p0) {
        if (p0) submit();
      });
      // 5秒后，无论是否上传完成，都进行提交
      Future.delayed(const Duration(seconds: 5), () {
        submit();
      });
    }
  }
}
